package com.ys.controller.api.finance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bo.dto.NameValueDto;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.PdfService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliCnyPayment;
import com.ys.entity.finance.TcwWanliCnyPaymentItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.finance.TcwWanliCnyPaymentService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwWanliCnyPayment")
public class ApiInterTcwWanliCnyPaymentController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TcwWanliCnyPayment> commonApiService;
	@Autowired
	private CommonApiService<TcwWanliCnyPaymentItem> commonApiServiceDetail;
	@Autowired
	private TcwWanliCnyPaymentService tcwWanliCnyPaymentService;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private PdfService pdfService;
	
	@RequiresPermissions("tcwWanliCnyPayment:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwWanliCnyPaymentItem cond){
		
		cond = setSeachSql(cond);
		return commonApiServiceDetail.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcwWanliCnyPayment:add")
	public R add(String bid, String depositPlatformCode, Integer drawingType, String remark, String subData) {
		try {
			//修改
			return tcwWanliCnyPaymentService.add(bid, depositPlatformCode, drawingType, remark, subData, MenuId.THR_VatApply);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("tcwWanliCnyPayment:add")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(String bid, String depositPlatformCode, Integer drawingType, String remark, String subData){
		try {
			return tcwWanliCnyPaymentService.edit(bid, depositPlatformCode, drawingType, remark, subData, MenuId.THR_VatApply);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("tcwWanliCnyPayment:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		TcwWanliCnyPayment tcwWanliCnyPayment = new TcwWanliCnyPayment().setId(id).queryFirst();
		try {
			return tcwWanliCnyPaymentService.flowPass(tcwWanliCnyPayment.getBid(), ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliCnyPayment:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		TcwWanliCnyPayment tcwWanliCnyPayment = new TcwWanliCnyPayment().setId(id).queryFirst();
		try {
			return tcwWanliCnyPaymentService.flowRefuse(tcwWanliCnyPayment.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwWanliCnyPayment:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		TcwWanliCnyPayment tcwWanliCnyPayment = new TcwWanliCnyPayment().setId(id).queryFirst();
		try {
			return yspTaskService.flowInit(tcwWanliCnyPayment.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tcwWanliCnyPaymentService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcwWanliCnyPayment:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliCnyPaymentItem cond) throws Exception{
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.THR_VatApply)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TcwWanliCnyPayment> util = new ExportExcelUtils<TcwWanliCnyPayment>(new TcwWanliCnyPayment());
        
        String toFilePath = util.exportExcel(listData, listField, "VAT申报单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliCnyPaymentItem setSeachSql(TcwWanliCnyPaymentItem cond){
    	
    	cond.addLeftJoin("TCW_WanliCnyPayment B ON B.Bid = A.Pbid")
	    		.addField("B.Bid bid")
	    		.addField("B.EffectStock effectStock")
    		.addLeftJoin("YS_ProcInst B99 ON B99.Bid = B.Bid")
	    		.addField("B99.UpdateTime auditTime")
	    		.addField("B99.CreateUserId createUserId")
    		.addLeftJoin("TS_UserInfo B100 ON B100.UserId = B99.CreateUserId")
	    		.addField("B100.UserId createUserId")
	    		.addField("B100.UserName createUserName");
    	
    	cond.addLeftJoin("THR_OperateCompanyApply B1 on B1.Vgsbm = A.Vgsbm")
			.addField("B1.Vgsjc vgsjc")
			
			.addLeftJoin("TCW_PartnerBankInfo C on C.Vid = A.PartnerBankInfoVid")
			.addField("C.Vyhzhmc partnerBankInfoVyhzhmc")
			.addField("C.Vyhzh partnerBankInfoVyhzh")
			.addField("C.Vkhh partnerBankInfoVkhh");
    	
    	cond.addLeftJoin("TCW_DepositPlatform D on D.Code = B.DepositPlatformCode")
			.addField("D.Code depositPlatformCode")
			.addField("D.Name depositPlatformName")
			.addField("D.PlatformName platformName");
    	
    	cond.addLeftJoin("TB_CompanyInfo F on F.Vid = D.CompanyVid")
			.addField("F.Vid companyVid")
			.addField("F.Vid companyName");
//    	
//    	cond.addLeftJoin("THR_OperateCompanyEuropeTrade B1 on B1.VatNo = A.VatNo")
//    		.addLeftJoin("THR_OperateCompanyApply B2 on B2.Vgsbm = B1.Vgsbm")
//			.addField("B2.Vgsbm vgsbm")
//    		.addField("B2.Vgsjc vgsjc")
//    		.addLeftJoin("TB_Country B3 on B3.Code = B1.CountryCode")
//			.addField("B3.Code countryCode")
//    		.addField("B3.Name countryName");
//    	
//    	cond.addLeftJoin("YS_ProcInst C ON C.Bid = B.Bid")
//    		.addField("C.UpdateTime auditTime");
//    	
//    	cond.addLeftJoin("TS_UserInfo D ON D.UserId = C.CreateUserId")
//    		.addField("D.UserId createUserId")
//    		.addField("D.UserName createUserName");
		
    	cond = commonApiServiceDetail.dataAuth(MenuId.TCW_WanliCnyPayment, cond);
        return  cond;
    }


	/**
	 * 打印
	 */
	@RequestMapping("/exportdy")
	@ResponseBody
	public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
		List<Map<String,Object>> infoList = new TcwWanliCnyPayment()
				.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
				.addField("U.DeptName AS deptName")//制单人部门
				.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间

				.addLeftJoin("TCW_DepositPlatform D on D.Code = A.DepositPlatformCode")
				.addField("D.Code depositPlatformCode")//账号编码
				.addField("D.Name depositPlatformName")//账号名称
				.addField("D.PlatformName platformName")//收款平台名称

				.addLeftJoin("TCW_WanliCnyPaymentItem S on S.Pbid = A.Bid")
				.addField("S.AmountIn amountIn")//汇入金额

				.setBid(bid)
				.queryMap();

		if(infoList!=null && infoList.size()>0){
			Map<String,Object> sonByOne = infoList.get(0);

			BigDecimal sonAmountTotal = BigDecimal.ZERO;
			for (Map<String, Object> son : infoList){
				sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("amountIn").toString()));
			}
			String nameStr =  (sonByOne.get("depositPlatformName")!=null ? sonByOne.get("depositPlatformName").toString():"")
					+ "/" + (sonByOne.get("depositPlatformCode")!=null ? sonByOne.get("depositPlatformCode").toString():"")
					+ "/" + (sonByOne.get("platformName")!=null ? sonByOne.get("platformName").toString():"");

			List<NameValueDto> listData = new ArrayList<>();
			listData.add(new NameValueDto("单据编号",bid));
			listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
			listData.add(new NameValueDto("申请部门",sonByOne.get("deptName").toString()));
			listData.add(new NameValueDto("付款账号",nameStr));
			listData.add(new NameValueDto("收款账号","合作商账户"));
			listData.add(new NameValueDto("付款类型","万里汇CNY付款"));
			listData.add(new NameValueDto("付款金额",sonAmountTotal.toString()));
			listData.add(new NameValueDto("付款说明",sonByOne.get("remark").toString()));
			String url = pdfService.generatePDF(bid,"万里汇CNY付款单", (sonByOne.get("depositPlatformName")!=null ? sonByOne.get("depositPlatformName").toString():""), sonByOne.get("createTimeByStr").toString(),listData);
			return R.ok(url);
		}else {
			return R.error("未查询到要导出的数据");
		}


	}
}
